package org.lwxyz.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.util.Set;

/**
 * @description 字符串操作类
 * @author yuwei
 * @version 1.0-SNAPSHOT
 * @date 2018/1/23
 */
public final class StringUtil extends StringUtils {

    /**
     * 隐藏构造函数
     */
    private StringUtil() {

    }

    /**
     * 最后一位是否是奇数，如果最后一位是字母，将其转成ascii码，再判断奇偶性
     *
     * @param string
     * @return
     */
    public static boolean endWithEven(String string) {
        if (isBlank(string)) {
            return false;
        }
        char c = string.toCharArray()[string.length() - 1];
        return c % 2 == 0;
    }

    /**
     * 最后一位数取余，返回余数
     * @param string
     * @param divisor
     * @return
     */
    public static Integer endResidue(String string, Integer divisor){
        if (isBlank(string)) {
            return -1;
        }
        char c = string.toCharArray()[string.length() - 1];
        return c % divisor;
    }

    /**
     * 将byte数组转换成16进制字符串
     *
     * @param bytes
     * @return
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 16进制字符串转换成byte数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || "".equals(hexString)) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * char转换成字节
     *
     * @param c
     * @return
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static Set<String> delimitedStrToSet(String delimitedString, String splitter){
        Set<String> set = Sets.newLinkedHashSet();
        if (StringUtil.isBlank(delimitedString)) {
            return set;
        }
        String[] appPkgs = delimitedString.split(splitter);
        for (String appPkg : appPkgs) {
            set.add(appPkg);
        }
        return set;
    }

    /**
     * 获取接口数据，并转为json
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public static JSONObject httpsRequestToJsonObject(String requestUrl, String requestMethod, String outputStr) throws Exception {
        StringBuffer buffer = httpsRequest(requestUrl, requestMethod, outputStr);
        return JSONObject.parseObject(buffer.toString());
    }

    /**
     * 获取接口数据，返回字符串
     * @param requestUrl
     * @param requestMethod
     * @param output
     * @return
     * @throws IOException
     */
    private static StringBuffer httpsRequest(String requestUrl, String requestMethod, String output) throws IOException {
        URL url = new URL(requestUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod(requestMethod);
        if (null != output) {
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(output.getBytes("UTF-8"));
            outputStream.close();
        }
        // 从输入流读取返回内容
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str;
        StringBuffer buffer = new StringBuffer();
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        connection.disconnect();
        return buffer;
    }

    /**
     * 将对象转为String
     * @param object
     * @return
     */
    public static String toString(Object object){
        if (object != null) {
            return object.toString();
        }
        return "";
    }
}
